<template>
	<view style="padding-bottom: 20px;" class="form">
		<uni-forms ref="valiForm" :rules="rules" :model="FormData" validate-trigger="blur" labelWidth="80px">
			<uni-forms-item label="标题" required name="title">
				<uni-easyinput :inputBorder='false' v-model="FormData.title" placeholder="请输入标题" />
			</uni-forms-item>
			<!-- <uni-forms-item label="预算">
				<view class="uni-flex"
					style="flex-flow: row nowrap; justify-content: space-between; align-items: center;">
					<uni-easyinput style="width: 80%;" :inputBorder='false' type="digit" v-model="FormData.price"
						placeholder="0.00" />
					<text>元</text>
				</view>
			</uni-forms-item> -->
			<uni-forms-item label="所属分类" required name="catgory">
				<!-- <uni-data-select :inputBorder='false' v-model="FormData.type" :localdata="typeList">
				</uni-data-select> -->
				<uni-data-picker placeholder="请选择分类" popup-title="请选择分类" :localdata="typeList"
					v-model="FormData.catgory" :map="props" @change="onchange" @nodeclick="onnodeclick"
					@popupopened="onpopupopened" @popupclosed="onpopupclosed">
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item label="联系电话" required name="phone">
				<uni-easyinput :inputBorder='false' v-model="FormData.phone" placeholder="请输入" />
			</uni-forms-item>
			<uni-forms-item label="微信号码">
				<uni-easyinput :inputBorder='false' v-model="FormData.weChat" placeholder="请输入" />
			</uni-forms-item>
			<uni-forms-item label="描述">
				<uni-easyinput maxlength="2000" :inputBorder='false' autoHeight type="textarea"
					v-model="FormData.description" @input="mathLength" placeholder="请输入描述" />
					<span style="float: right; color: #333;">{{length}}/65535</span>
			</uni-forms-item>
			<view style="margin-bottom: 20px;">
				<uni-file-picker ref="imageUpload" @select="select" limit="1" fileMediatype="image" v-model="imageValue"
					file-extname="png,jpg" :image-styles="imageStyles" return-type="object">
					<view class="takephoto">
						<uni-icons type="camera" color="#00B5DD" size="28"></uni-icons>
						<text>添加图片</text>
					</view>
				</uni-file-picker>
			</view>
			<button class="customer-btn" :loading='loading' @click="submit(FormData)">立即发布</button>
		</uni-forms>
	</view>
</template>

<script>
	import {
		queryDictDataTree,
		addFarmSeek,
		uploadFile
	} from "@/api/user.js";
	export default {
		data() {
			return {
				imageValue: {},
				imageStyles: {
					width: 64,
					height: 64,
					border: {
						color: "#D4D6D9",
						width: 1,
						style: 'dashed',
						radius: '8px'
					}
				},
				FormData: {
					title: '',
					price: '',
					catgory: '',
					description: '',
					phone: '',
					image: '',
					providerName: '',
					resume: '',
					weChat: ''
				},
				props: {
					text: 'name',
					value: 'code'
				},
				typeList: [],
				rules: {
					title: {
						rules: [{
							required: true,
							errorMessage: '标题不能为空'
						}]
					},
					catgory: {
						rules: [{
							required: true,
							errorMessage: '请选择分类'
						}]
					},
					// price: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '价格不能为空'
					// 	}]
					// },

					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入手机号码'
						}, {
							validateFunction: function(rule, value, data, callback) {
								console.log('phone', value)
								// if (value.length != 11 ) {
								// 	callback('请输入正确的手机号码')
								// }
								var reg = /^1\d{10}$/;
								if (!reg.test(value)) {
									callback('请输入正确的手机号码')
								}
								return true	
							}
						}, {
							validateFunction: function(rule, value, data, callback) {
								console.log('phone', value)
								if (value.length != 11 ) {
									callback('请输入正确的手机号码')
								}
								return true	
							}
						}]
					}
				},
				loading: false,
				length:0
			}
		},
		onReady() {
			// 设置自定义表单校验规则，必须在节点渲染完毕后执行
			// this.$nextTick(() => {
			// 	this.$refs.valiForm.setRules(this.rules)
			// })
			this.$refs.valiForm.setRules(this.rules)
		},
		methods: {
			async queryDictDataTree(options) {
				const res = await queryDictDataTree(options)
				let temp = JSON.stringify(res.returnObj);
				temp = temp.replace(/subDictDataList/g,"children")
				this.typeList = JSON.parse(temp)
			},

			async addFarmSeek(options) {
				const res = await addFarmSeek(options);
				this.loading = false
				console.log("res", res)
				if (res.success) {
					uni.showToast({
						title: "农户求助发布成功！",
						icon: "success",
						duration: 4500
					}).then(() => {
						uni.navigateBack();
					})
				}
			},

			async uploadFile(options) {
				const res = await uploadFile(options);
				console.log('uploadFileRes', res);
				this.FormData.image = res.returnObj
			},

			select(e) {
				console.log(e)
				const tempFilePaths = e.tempFilePaths;
				//获取图片临时路径
				const imgUrl = tempFilePaths[0];
				const name = e.tempFiles[0].name;
				this.uploadFile(imgUrl);
				/* uni.uploadFile({
					url: "https://1yj-rt.gfox.ltd/nongmao/nb-as/1.0.1/FileService/uploadFile",
					filePath: imgUrl,
					name:"file",
					// header: {
					// 	// 'Content-Type': 'application/x-www-form-urlencoded'
					// 	'Content-Type': 'multipart/form-data' //自定义请求头信息
					// },
					success: (uploadFileRes) => {
					            console.log('uploadFileRes', uploadFileRes.data);
					            const res = uploadFileRes.data
					            this.FormData.image = JSON.parse(res).returnObj;  
					            //处理数据
					            //const path=JSON.parse(uploadFileRes.data)
					            //赋值，前端渲染
					            //this.baseFormData.photo=path.imgUrl
					          },
					fail:(err)=>{
						console.log('err')
					},
				    complete:()=>{
					}
				}) */
			},
			submit(ref) {
				this.$refs['valiForm'].validate().then(res => {
					console.log('success', ref.price);
					let tempobj = ref;
					let price = this.toDecimal2(ref.price);
					tempobj.price = price;
					this.loading = true
					this.addFarmSeek(tempobj);
				}).catch(err => {
					console.log('err', err);
					uni.showToast({
						title:err[0].errorMessage
					})
				})
			},
			mathLength(){
				this.length = this.FormData.description.length
			},
			toDecimal2(x) {
				if(!x){
					return x
				}
				var f = parseFloat(x);
				if (isNaN(f)) {
					return false;
				}
				var f = Math.round(x * 100) / 100;
				var s = f.toString();
				var rs = s.indexOf('.');
				if (rs < 0) {
					rs = s.length;
					s += '.';
				}
				while (s.length <= rs + 2) {
					s += '0';
				}
				return s;
			},
			onnodeclick(e) {
				console.log(e);
			},
			onpopupopened(e) {
				if (this.typeList.length == 0) {
					this.queryDictDataTree({
						"dictType": "SERVICE_CATGORY"
					})
				}
				console.log('popupopened');
			},
			onpopupclosed(e) {
				console.log('popupclosed');
			},
			onchange(e) {
				console.log('onchange:', e);
			}
		},
		onLoad() {
			this.queryDictDataTree({
				"dictType": "SERVICE_CATGORY"
			})
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.takephoto {
		border-radius: 8px;
		background-color: #F4F5F6;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.file-picker__box {
		width: 100% !important;
		height: 116px !important;
	}

	.customer-btn {
		background-color: #00B5DD !important;
		color: #fff;
		width: 100%;
		border-radius: 8px;
		height: 44px;
		line-height: 44px;
		font-size: 32rpx;
		font-weight: 500;
		margin-top: 50px;
	}
</style>